package com.sduept.nwld.dataserver.manager.etl;

import com.sduept.bigdata.fault.common.ETLDAO;
import com.sduept.bigdata.fault.facde.FaultGenerateFacde;
import com.sduept.cim.model.wires.ACLineSegment;
import com.sduept.core.dao.SuperDAO;
import com.sduept.generator.ObjectId;
import com.sduept.nwld.dataserver.interceptors.TzxxWarnInterceptor;
import com.sduept.nwld.dataserver.manager.cim.CimManager;
import com.sduept.nwld.dataserver.model.daily.Tripping;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.interceptor.Interceptors;
import java.util.*;

/**
 * 跳闸记录抽取故障记录
 * 
 * @author Xiaopy
 *
 */
@Service
@Slf4j
public class TZRecordETLManager {

	@Autowired
	private SuperDAO dao;
	@Autowired
	private ETLDAO eDao;
	@Autowired
	private CimManager cm;
	@Autowired
	private FaultGenerateFacde facde;

	public List<Tripping> receiveAndSaveAllData() {
		List<?> list = getAllSourceData();
		Map<String, ACLineSegment> aclineMap = getAclineMap();
		List<Tripping> recordList = object2Record(list, aclineMap,getLt500AclineMap());
		tzToFault(recordList);
		saveToBean(recordList);
		//this.sessionContext.getBusinessObject(TZRecordETLManager.class).saveToBean(recordList);
		return recordList;
	}
	@Interceptors({TzxxWarnInterceptor.class})
	public List<Tripping>  receiveAndSavePartData(String date) {
		List<?> list = getAllSourceData(date);
		Map<String, ACLineSegment> aclineMap = getAclineMap();
		List<Tripping> recordList = object2Record(list, aclineMap,getLt500AclineMap());
		tzToFault(recordList);
		saveToBean(recordList);
		return recordList;
	}

	public List<?> getAllSourceData() {
		List<?> result = eDao.query(" select cim_fzsj,cim_dydj,cim_xlmc,cim_czmc1,cim_czmc2,cim_kgmc from t_oms_tzxx ");
		return result;
	}

	public List<?> getAllSourceData(String date) {
		String sql = " select cim_fzsj,cim_dydj,cim_xlmc,cim_czmc1,cim_czmc2,cim_kgmc from t_oms_tzxx " + " where update_time=";
		List<?> result = eDao.query(sql + "'" + date + "' order by cim_fzsj asc");
		return result;
	}
	
	public void saveToBean(List<Tripping> recordList) {
		for(Tripping trip:recordList){
			dao.createOrUpdate(trip, Tripping.class);
		}
		log.info("更新跳闸信息："+recordList.size());
//		try {
//			dao.persistentBatch(Tripping.class, recordList);
//		} catch (SQLException e) {
//			e.printStackTrace();
//		}
	}
	/**
	 * 500kV 及以上线路
	 * @return
	 */
	private Map<String, ACLineSegment> getAclineMap() {
		Map<String, ACLineSegment> resultMap = new HashMap<String, ACLineSegment>();
		List<ACLineSegment> lineSegement = cm.getAcLineSegmentsBystandVoltagelevel500();
		for (ACLineSegment acline : lineSegement) {
			if (StringUtils.isNotEmpty(acline.getName())) {
				resultMap.put(acline.getName(), acline);
			}
		}
		return resultMap;
	}
	
	/**
	 * <500 的线路map
	 * @return
	 */
	private Map<String, ACLineSegment> getLt500AclineMap() {
		Map<String, ACLineSegment> resultMap = new HashMap<String, ACLineSegment>();
		List<ACLineSegment> lineSegement = cm.getAcLineSegments(null, (float)499);
		for (ACLineSegment acline : lineSegement) {
			if (StringUtils.isNotEmpty(acline.getName())) {
				resultMap.put(acline.getName(), acline);
			}
		}
		return resultMap;
	}
	
	private void bindEquipment(Tripping trip, Map<String, ACLineSegment> aclineMap) {
		// 获取故障线路以及线路ID
		if (StringUtils.isNotEmpty(trip.getLineName())) {
			ACLineSegment acLineSegment = aclineMap.get(trip.getLineName());
			if (null == acLineSegment) {
				ACLineSegment rtn = queryLineCimId(trip.getLineName(), aclineMap.values());
				if (null != rtn) {
					trip.setLineId(rtn.getId());
				}
			} else {
				trip.setLineId(acLineSegment.getId());
			}
		}
	}

	private List<Tripping> object2Record(List<?> list, Map<String, ACLineSegment> aclineMap,Map<String, ACLineSegment> lt500Map) {
		List<Tripping> result = new ArrayList<>();
		for (Object obj : list) {
			Object[] objs = (Object[]) obj;
			Tripping trip = new Tripping();
			trip.setId(ObjectId.get().toString());
			trip.setTripTime((Date) objs[0]);
			trip.setVoltageClass((String) objs[1]);
			trip.setLineName((String) objs[2]);
			trip.setStationName1((String) objs[3]);
			trip.setStationName2((String) objs[4]);
			trip.setSwitchName((String) objs[5]);
			if (StringUtils.isNotEmpty(trip.getVoltageClass())) {
				// 电压等级
				String voltage = trip.getVoltageClass().replaceAll("[^\\d]", "");
				Integer vol = 500;
				try {
					vol = Integer.parseInt(voltage);
				} catch (Exception e) {
					log.error("数字解析出错");
				}
				if (vol < 500) {
					bindEquipment(trip, lt500Map);
				} else {
					bindEquipment(trip, aclineMap);
				}
			}
			result.add(trip);
		}
		return result;
	}

	private ACLineSegment queryLineCimId(String lineName, Collection<ACLineSegment> list) {
		ACLineSegment rtn = cm.getACLineSegmentByName(lineName, list);
		return rtn;
	}

	/**
	 * 将跳闸记录抽取到故障列表中
	 * 
	 * @param objs
	 */
	private void tzToFault(List<Tripping> recordList) {
		for (Tripping trip : recordList) {
			if (null != trip.getSwitchName() && trip.getSwitchName().contains("极1")) {
				log.warn("该跳闸记录为实验数据，不会生成故障记录：" + (trip.getLineId() + "---" + trip.getTripTime()));
				continue;
			}
			facde.generateFaultByTriping(trip.getId(), trip.getTripTime(), trip.getLineId(),trip.getSwitchName());
		}
	}
}
